package com.robusta.cityuate.activities;

import java.util.Calendar;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.robusta.cityuate.R;
import com.robusta.cityuate.base.CityuateFragmentActivity;
import com.robusta.cityuate.dialogs.DatePickerFragment;
import com.robusta.cityuate.dialogs.TimePickerFragment;
import com.robusta.cityuate.objects.Offering;
import com.robusta.cityuate.objects.Spot;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.services.HTTPService;
import com.robusta.cityuate.services.OfferingCreateEditService;
import com.robusta.cityuate.utils.ConnectionUtils;
import com.robusta.cityuate.utils.TimeUtils;

public class OfferingCreateEditActivity extends CityuateFragmentActivity implements
		TextWatcher, OnSeekBarChangeListener, OnCheckedChangeListener {

	public static final int OFFER_CREATEEDIT_CODE = 11;

	
	
	private static final String TAG = OfferingCreateEditActivity.class.getName();
	
	private SeekBar ratingSeekBar;
	private TextView ratingNum;
	private TextView offerName;
	private TextView creditRate;
	private TextView startDate;
	private TextView endDate;
	private TextView startTime;
	private TextView endTime;
	private CheckBox reccuringCheck;
	private LinearLayout reccuringPart;
	private RadioGroup recurringType;
	private TextView expiryDate;
	private Button creatBottun;
	private Context mContext = this;
//	private ProgressDialog dialog;
	private Offering currenOffer;
	public static final String IS_EDIT = "isEdit";

	private CityuateBroadCastReceiver receiver = new CityuateBroadCastReceiver() {

		@Override
		public void onSuccess() {
			createOfferingSuccess();
		}

		@Override
		public void onFailure() {
			createOfferingFail();
		}

		@Override
		public void onCancel() {
			setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, TAG);
		}

	};
	private boolean isEdit;
	private Calendar sDate;
	private Calendar eDate;
	private Calendar expDate;
	private Spot spot;
	private ActionBar mActionBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.offering_create_edit_view);
		mActionBar = getSupportActionBar();
		ratingSeekBar = (SeekBar) findViewById(R.id.rating_seekbar);
		ratingSeekBar.setOnSeekBarChangeListener(this);
		ratingNum = (TextView) findViewById(R.id.rating);
		ratingNum.setText(ratingSeekBar.getProgress() + "");
		offerName = (TextView) findViewById(R.id.offering_name);
		creditRate = (TextView) findViewById(R.id.credit_rate);
		startDate = (TextView) findViewById(R.id.start_date);
		startTime = (TextView) findViewById(R.id.start_time);
		endDate = (TextView) findViewById(R.id.end_date);
		endTime = (TextView) findViewById(R.id.end_time);
		reccuringCheck = (CheckBox) findViewById(R.id.reccuring_check);
		reccuringPart = (LinearLayout) findViewById(R.id.reccuring_part);
		reccuringCheck.setOnCheckedChangeListener(this);
		recurringType = (RadioGroup) findViewById(R.id.reccuring_type);
		expiryDate = (TextView) findViewById(R.id.expiry_date);
		creatBottun = (Button) findViewById(R.id.btn_create);

		// Log.e(TAG,""+(offerName==null));
		offerName.addTextChangedListener(this);
		creditRate.addTextChangedListener(this);
		startDate.addTextChangedListener(this);
		endDate.addTextChangedListener(this);
		startTime.addTextChangedListener(this);
		endTime.addTextChangedListener(this);
		expiryDate.addTextChangedListener(this);

		Bundle extras = getIntent().getExtras();
		if (extras != null)
			isEdit = extras.getBoolean(IS_EDIT, false);

		if (!isEdit)
			spot = (Spot) getIntent().getExtras().getSerializable(Spot.SPOT);
		else {// if edit set fields values
			currenOffer = (Offering) extras.getSerializable(Offering.OFFERING);
			spot = currenOffer.getSpot();
			offerName.setText(currenOffer.getName());
			creditRate.setText((int)currenOffer.getCreditRate() + "");
			startTime.setText(TimeUtils.formatDate(currenOffer.getStartTime(),
					TimeUtils.TIME_FORMAT));
			endTime.setText(TimeUtils.formatDate(currenOffer.getEndTime(),
					TimeUtils.TIME_FORMAT));
			startDate.setText(TimeUtils.formatDate(currenOffer.getStartTime(),
					TimeUtils.DATE_FORMAT));
			endDate.setText(TimeUtils.formatDate(currenOffer.getEndTime(),
					TimeUtils.DATE_FORMAT));
			ratingSeekBar.setProgress((int) currenOffer.getMinRating());
		
			if (currenOffer.getRecurring()!=null&&!currenOffer.getRecurring().equals("")) {
				reccuringCheck.toggle();
				if (currenOffer.getRecurring().equals("w"))
					recurringType.check(R.id.weekly);
				
				expiryDate.setText(TimeUtils.formatDate(
						currenOffer.getExpiryDate(),
						TimeUtils.DATE_FORMAT));
			}
			creatBottun.setText(R.string.update);

		}

		mActionBar.setTitle(spot.getName());
		mActionBar.setSubtitle(R.string.create_new_offering);

	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(receiver, new IntentFilter(TAG));

		if (!ConnectionUtils.isConnecting(mContext, TAG))
		// it was connected
		{
			if (ConnectionUtils.wasConnected(mContext, TAG))
				// connection was successful
				if (ConnectionUtils.isResultSuccessful(mContext, TAG))
					createOfferingSuccess();
				else
					// it failed
					createOfferingFail();
		} else { // there is an active connection
			setSupportProgressBarIndeterminateVisibility(true);
			disableView();
		}

	}

	@Override
	protected void onPause() {

		super.onPause();
		unregisterReceiver(receiver);
		if (!ConnectionUtils.isConnecting(mContext, TAG)) {
			ConnectionUtils.clearConnection(mContext, TAG);
		}

//		if (dialog != null) {
//			dialog.cancel();
//			dialog = null;
//		}

	}

	public void showDatePicker(View v) {
		DialogFragment newFragment = DatePickerFragment
				.getInstance(v.getId(),Calendar.getInstance(),null);
		newFragment.show(getSupportFragmentManager(), DatePickerFragment.DATE_PICKER_TAG);
	}

	public void showTimePicker(View v) {
		DialogFragment newFragment = TimePickerFragment
				.getInstance(v.getId());
		newFragment.show(getSupportFragmentManager(), TimePickerFragment.TIME_PICKER_TAG);
	}

	// seekBar methods
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		ratingNum.setText(progress + "");
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
	}

	// text watcher methods
	@Override
	public void afterTextChanged(Editable arg0) {
		if (ratingNum.length() != 0 && offerName.length() != 0
				&& startDate.length() != 0 && endDate.length() != 0
				&& startTime.length() != 0 && endTime.length() != 0
				&& creditRate.length() != 0)
			if (reccuringCheck.isChecked())
				if (expiryDate.length() != 0)
					creatBottun.setEnabled(true);
				else
					creatBottun.setEnabled(false);
			else
				creatBottun.setEnabled(true);
		else
			creatBottun.setEnabled(false);
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
	}

	/**
	 * fires a createOfferingService
	 * 
	 * @param v
	 */
	public void createNewOffering(View v) {

		if (!checkDates())
			return;
		// Check if no connection pop up a dialog
		if (!ConnectionUtils.isNetworkAvailable(mContext)) {
			// No connection
			ConnectionUtils.showNoConnectionDialog(mContext);
			return;
		} else { // Connection is available

			// Start loading dialog and connecting variables
			disableView();
			setSupportProgressBarIndeterminateVisibility(true);
			// start back-ground service to handle registration process
			Intent backgroud_regService = new Intent(this,
					OfferingCreateEditService.class);
			backgroud_regService.setAction(TAG);
			backgroud_regService.putExtra(HTTPService.LOGIN_RQUIRED, true);
			backgroud_regService.putExtra(Spot.SPOT, spot);
			backgroud_regService.putExtra(IS_EDIT,isEdit);
			if(isEdit)
				backgroud_regService.putExtra(Offering.OFFERING_ID, currenOffer.getId());
			backgroud_regService.putExtra(Offering.OFFERING_NAME, offerName
					.getText().toString());
			backgroud_regService.putExtra(Offering.OFFERING_RATE, creditRate
					.getText().toString());
			backgroud_regService.putExtra(Offering.OFFERING_MIN_RATING,
					ratingNum.getText().toString());
			// start Date
			backgroud_regService.putExtra(Offering.OFFERING_START_TIME_1I,
					sDate.get(Calendar.YEAR));
			backgroud_regService.putExtra(Offering.OFFERING_START_TIME_2I,
					sDate.get(Calendar.MONTH) + 1);
			backgroud_regService.putExtra(Offering.OFFERING_START_TIME_3I,
					sDate.get(Calendar.DAY_OF_MONTH));
			backgroud_regService.putExtra(Offering.OFFERING_START_TIME_4I,
					sDate.get(Calendar.HOUR_OF_DAY));
			backgroud_regService.putExtra(Offering.OFFERING_START_TIME_5I,
					sDate.get(Calendar.MINUTE));
			// end Date
			backgroud_regService.putExtra(Offering.OFFERING_END_TIME_1I,
					eDate.get(Calendar.YEAR));
			backgroud_regService.putExtra(Offering.OFFERING_END_TIME_2I,
					eDate.get(Calendar.MONTH) + 1);
			backgroud_regService.putExtra(Offering.OFFERING_END_TIME_3I,
					eDate.get(Calendar.DAY_OF_MONTH));
			backgroud_regService.putExtra(Offering.OFFERING_END_TIME_4I,
					eDate.get(Calendar.HOUR_OF_DAY));
			backgroud_regService.putExtra(Offering.OFFERING_END_TIME_5I,
					eDate.get(Calendar.MINUTE));

			if (reccuringCheck.isChecked()) {
				backgroud_regService
						.putExtra(
								Offering.OFFERING_RECURRING,
								(recurringType.getCheckedRadioButtonId() == R.id.weekly) ? "w"
										: "d");
				// Expiry
				backgroud_regService.putExtra(Offering.OFFERING_EXPIRY_1I,
						expDate.get(Calendar.YEAR));
				backgroud_regService.putExtra(Offering.OFFERING_EXPIRY_2I,
						expDate.get(Calendar.MONTH) + 1);
				backgroud_regService.putExtra(Offering.OFFERING_EXPIRY_3I,
						expDate.get(Calendar.DAY_OF_MONTH));

			}
			startService(backgroud_regService);

		}

	}

	/**
	 * check if the dates follows the rules must be called before firing service
	 * 
	 * @return
	 */
	private boolean checkDates() {
		String startTimeS = startDate.getText().toString() + "T"
				+ startTime.getText().toString();
		sDate = TimeUtils.getCalendarFromFormat(startTimeS, TimeUtils.IN_DATE_TIME_FORMAT);

		String endTimeS = endDate.getText().toString() + "T"
				+ endTime.getText().toString();
		eDate = TimeUtils.getCalendarFromFormat(endTimeS, TimeUtils.IN_DATE_TIME_FORMAT);

		if (eDate.getTimeInMillis() - sDate.getTimeInMillis() < 30 * 60000) {
			Toast.makeText(mContext, getString(R.string.min_duration),
					Toast.LENGTH_LONG).show();
			return false;
		}

		if (reccuringCheck.isChecked()) {
			expDate = TimeUtils.getCalendarFromFormat(expiryDate.getText()
					.toString(), TimeUtils.DATE_FORMAT);

			if (expDate.getTimeInMillis() - eDate.getTimeInMillis() > 2l * 30
					* 24 * 60 * 60000) {
				Toast.makeText(mContext, getString(R.string.max_expiry),
						Toast.LENGTH_LONG).show();
				return false;
			}

		}

		return true;
	}

	/**
	 * success scenario
	 */
	private void createOfferingSuccess() {
		setSupportProgressBarIndeterminateVisibility(false);
		enableView();
		setResult(RESULT_OK);
		if (!isEdit)
			Toast.makeText(mContext, getString(R.string.offer_created),
					Toast.LENGTH_LONG).show();
		else
			Toast.makeText(mContext, getString(R.string.offer_edited),
					Toast.LENGTH_LONG).show();
		finish();
	}

	/**
	 * failure scenario
	 */
	private void createOfferingFail() {
		setSupportProgressBarIndeterminateVisibility(false);
		// show failure message
		enableView();
		Toast.makeText(mContext, ConnectionUtils.getExtra(mContext, TAG),
				Toast.LENGTH_LONG).show();
		ConnectionUtils.clearConnection(mContext, TAG);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			reccuringPart.setVisibility(View.VISIBLE);
			afterTextChanged(null);
		} else {
			reccuringPart.setVisibility(View.GONE);
			afterTextChanged(null);
		}
	}
	
	private void disableView() {
		offerName.setEnabled(false);
		creditRate.setEnabled(false);
		startDate.setEnabled(false);
		endDate.setEnabled(false);
		startTime.setEnabled(false);
		endTime.setEnabled(false);
		expiryDate.setEnabled(false);
		reccuringCheck.setEnabled(false);
		recurringType.setEnabled(false);
		creatBottun.setEnabled(false);
	}
	
	
	private void enableView(){
		offerName.setEnabled(true);
		creditRate.setEnabled(true);
		startDate.setEnabled(true);
		endDate.setEnabled(true);
		startTime.setEnabled(true);
		endTime.setEnabled(true);
		expiryDate.setEnabled(true);
		reccuringCheck.setEnabled(true);
		recurringType.setEnabled(true);
		creatBottun.setEnabled(true);
	}
	
	@Override
	public void onBackPressed() {
		if (ConnectionUtils.isConnecting(mContext, TAG)) {
			enableView();
			setSupportProgressBarIndeterminateVisibility(false);
			Intent loginCancel = new Intent(TAG + HTTPService.CANCEL);
			sendBroadcast(loginCancel);
			ConnectionUtils.clearConnection(mContext, TAG);
		} else
			super.onBackPressed();
	}

}
